<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <el-form-item label="列表封面图" prop="picUrl" required>
        <UploadImg
          v-model="formData.picUrl"
          :file-size="2"
          :height="'120px'"
          :width="'120px'"
        >
          <template #tip>
            <span>建议尺寸：800*600，格式：JPG、PNG，大小不超过2MB</span>
          </template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="课程主题" prop="title" required>
        <el-input v-model="formData.title" placeholder="请输入(必填项)" />
      </el-form-item>
      <el-form-item label="课程概述" prop="description">
        <el-input
          v-model="formData.description"
          type="textarea"
          placeholder="请输入(必填项)"
          :rows="4"
        />
      </el-form-item>
      <el-form-item label="售价" prop="price" required>
        <el-input-number
          v-model="formData.price"
          :min="0"
          :precision="2"
          :step="0.1"
          style="width: 150px"
        />
        <el-select v-model="formData.priceUnit" class="ml-10px" style="width: 100px">
          <el-option label="元" value="yuan" />
          <el-option label="积分" value="point" />
        </el-select>
      </el-form-item>
      <el-form-item label="所属分类" prop="categoryId" required>
        <el-select
          v-model="formData.categoryId"
          placeholder="请选择所属分类"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="category in categoryOptions"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="主讲人" prop="speaker" required>
        <el-input v-model="formData.speaker" placeholder="请输入(必填项)" />
      </el-form-item>
      <el-form-item label="头像" prop="headUrl">
        <UploadImg
          v-model="formData.headUrl"
          :file-size="2"
          :height="'120px'"
          :width="'120px'"
        >
          <template #tip>
            <span>建议尺寸：200*200，格式：JPG、PNG，大小不超过2MB</span>
          </template>
        </UploadImg>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="submitForm">确 定</el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import * as CourseApi from '@/api/course/info'
import { CourseInfoVO } from '@/api/course/info'
import * as CategoryApi from '@/api/course/category'
import { CategoryVO } from '@/api/course/category'
import UploadImg from '@/components/UploadFile/src/UploadImg.vue'

defineOptions({ name: 'CourseForm' })

const message = useMessage() // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formRef = ref<FormInstance>() // 表单 Ref
const formLoading = ref(false) // 表单的加载中

const formData = ref<Partial<CourseInfoVO> & {
  priceUnit: string;
  description: string;
}>({
  id: undefined,
  picUrl: '',
  title: '',
  description: '',
  price: 0,
  priceUnit: 'yuan',
  categoryId: undefined,
  speaker: '',
  headUrl: ''
})
const formRules = reactive({
  picUrl: [{ required: true, message: '请上传列表封面图', trigger: 'blur' }],
  title: [{ required: true, message: '请输入课程主题', trigger: 'blur' }],
  price: [{ required: true, message: '请输入售价', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择所属分类', trigger: 'change' }],
  speaker: [{ required: true, message: '请输入主讲人', trigger: 'blur' }]
})

// 定义分类选项类型
interface CategoryOption {
  id: number;
  name: string;
}

// 存储完整的分类数据，用于获取分类路径
const categoryData = ref<CategoryVO[]>([])

// 分类选项
const categoryOptions = ref<CategoryOption[]>([])

// 获取课程分类列表
const getCategoryOptions = async () => {
  try {
    const res = await CategoryApi.getCategoryList()
    // 保存完整的分类数据
    categoryData.value = res.list || []
    
    // 使用递归函数处理嵌套的类目数据
    const flattenCategories: CategoryOption[] = [];

    // 递归函数，将树形结构展平为一维数组
    const flatten = (items: CategoryVO[], prefix = '') => {
      items.forEach(item => {
        // 添加当前类目到选项列表
        flattenCategories.push({
          id: item.id!,
          name: prefix + item.categoryName
        });

        // 如果有子类目，递归处理
        if (item.childrenCategory && item.childrenCategory.length > 0) {
          flatten(item.childrenCategory, prefix + item.categoryName + ' / ');
        }
      });
    };

    // 调用递归函数处理数据
    flatten(res.list || []);

    // 更新选项列表
    categoryOptions.value = flattenCategories;
  } catch (error) {
    console.error('获取课程分类失败', error)
    message.error('获取课程分类失败')
  }
}

/** 打开弹窗 */
const open = async (_type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = id ? '编辑课程信息' : '创建课程信息'
  resetForm()

  // 获取分类选项
  await getCategoryOptions()

  // 修改时，获取课程详情
  if (id) {
    formLoading.value = true
    try {
      const res = await CourseApi.getCourseInfo(id)
      // 将API返回的数据映射到表单数据
      formData.value = {
        ...formData.value,
        id: res.data.id,
        picUrl: res.data.picUrl,
        title: res.data.title,
        description: res.data.courseIntroduction || '',
        price: (res.data.price || 0) / 100, // 分转元
        priceUnit: 'yuan',
        categoryId: res.data.categoryId,
        speaker: res.data.speaker,
        headUrl: res.data.headUrl
      }
    } catch (error) {
      console.error('获取课程详情失败', error)
      message.error('获取课程详情失败')
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const emit = defineEmits(['success'])
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  await formRef.value.validate()

  formLoading.value = true
  try {
    // 获取分类路径
    const categoryPath = getCategoryPath(formData.value.categoryId)
    // 获取分类名称路径
    const categoryPathName = getCategoryPathName(formData.value.categoryId)
    
    // 准备提交的数据
    const submitData: CourseInfoVO = {
      id: formData.value.id,
      picUrl: formData.value.picUrl,
      title: formData.value.title,
      courseIntroduction: formData.value.description,
      price: Math.round((formData.value.price || 0) * 100), // 元转分
      categoryId: formData.value.categoryId,
      categoryPath: categoryPath, // 添加分类路径参数
      categoryPathName: categoryPathName, // 添加分类名称路径参数
      speaker: formData.value.speaker,
      headUrl: formData.value.headUrl,
      enableStatus: 1,
    }

    // 根据是否有ID判断是创建还是更新
    if (formData.value.id) {
      await CourseApi.updateCourseInfo(submitData)
      message.success('更新课程成功')
    } else {
      await CourseApi.createCourseInfo(submitData)
      message.success('创建课程成功')
    }

    // 关闭弹窗，通知父组件刷新
    dialogVisible.value = false
    emit('success')
  } catch (error) {
    console.error('提交课程数据失败', error)
    message.error('提交课程数据失败')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    picUrl: '',
    title: '',
    description: '',
    price: 0,
    priceUnit: 'yuan',
    categoryId: undefined,
    speaker: '',
    headUrl: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

/**
 * 获取分类路径，返回逗号分隔的ID字符串
 */
const getCategoryPath = (categoryId?: number): string => {
  if (!categoryId) return ''
  
  // 存储找到的所有父级ID
  const pathIds: number[] = []
  
  // 递归查找父级ID
  const findPath = (categories: CategoryVO[], targetId: number): boolean => {
    for (const category of categories) {
      // 如果找到目标ID
      if (category.id === targetId) {
        pathIds.push(category.id)
        return true
      }
      
      // 如果有子类目，递归查找
      if (category.childrenCategory && category.childrenCategory.length > 0) {
        if (findPath(category.childrenCategory, targetId)) {
          // 如果在子类目中找到，将当前类目ID添加到路径中
          pathIds.unshift(category.id!)
          return true
        }
      }
    }
    
    return false
  }
  
  // 开始查找路径
  findPath(categoryData.value, categoryId)
  
  // 返回逗号分隔的ID字符串
  return pathIds.join(',')
}

/**
 * 获取分类名称路径，返回分类名称字符串，格式为「一级类目/二级类目」
 */
const getCategoryPathName = (categoryId?: number): string => {
  if (!categoryId) return ''
  
  // 存储找到的所有父级名称
  const pathNames: string[] = []
  
  // 递归查找父级名称
  const findPathName = (categories: CategoryVO[], targetId: number): boolean => {
    for (const category of categories) {
      // 如果找到目标ID
      if (category.id === targetId) {
        pathNames.push(category.categoryName)
        return true
      }
      
      // 如果有子类目，递归查找
      if (category.childrenCategory && category.childrenCategory.length > 0) {
        if (findPathName(category.childrenCategory, targetId)) {
          // 如果在子类目中找到，将当前类目名称添加到路径中
          pathNames.unshift(category.categoryName)
          return true
        }
      }
    }
    
    return false
  }
  
  // 开始查找路径
  findPathName(categoryData.value, categoryId)
  
  // 返回斜杠分隔的名称字符串
  return pathNames.join('/')
}

// 暴露给外部使用
defineExpose({
  open
})
</script>
